﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace Hisuntech.SystemFramework.Net.Mail
{
    /// <summary>
    /// 邮件服务器类型
    /// </summary>
    public enum MailServerType
    { 
        /// <summary>
        /// 发件服务器
        /// </summary>
        SMTP,
        /// <summary>
        /// 收件服务器
        /// </summary>
        POP3,
        /// <summary>
        /// IBM Lotus Notes 邮件服务器，可以同时收发邮件
        /// </summary>
        Notes
    }
    /// <summary>
    /// 邮件配置
    /// </summary>
    public  class MailConfig
    {
        /// <summary>
        /// 获取发邮件的邮件服务配置，在应用程序配置节，要求配置信息MailServer，ServerUsername，ServerPassword，MailPort
        /// </summary>
        /// <returns></returns>
        public static MailServerInfo GetConfig()
        {
            return GetConfig(MailServerType.SMTP);
        }

        /// <summary>
        /// 账号密码是否加密
        /// </summary>
        /// <returns></returns>
        private static bool IsSecurityCfg()
        {
            bool isSecurity = false;
            if (ConfigurationManager.AppSettings["Security"] != null)
            {
                if (ConfigurationManager.AppSettings["Security"].ToUpper() == "TRUE")
                {
                    isSecurity = true;
                }
            }
            return isSecurity;
        }

        /// <summary>
        /// 获取邮件服务配置，在应用程序配置节，要求具有SMTP_或者POP3_打头的配置信息MailServer，ServerUsername，ServerPassword，MailPort
        /// </summary>
        /// <param name="svrType">邮件服务器的类型</param>
        /// <returns></returns>
        public static MailServerInfo GetConfig(MailServerType svrType)
        {
            if (svrType == MailServerType.Notes)
                svrType = MailServerType.POP3;//Notes 邮箱收发邮件都采用POP3设置

            string typeName = svrType.ToString()+"_";
            MailServerInfo cfg = new MailServerInfo();
            cfg.MailServer = ConfigurationManager.AppSettings[typeName+"MailServer"];//"pop3.163.com";
            cfg.ServerUsername = ConfigurationManager.AppSettings[typeName + "ServerUsername"];// "mfkaudx@163.com";
            cfg.ServerPassword = ConfigurationManager.AppSettings[typeName + "ServerPassword"]; //"tinger$$*)*^&";
            cfg.MailPort = int.Parse(ConfigurationManager.AppSettings[typeName + "MailPort"]);//  110;
            if (svrType == MailServerType.SMTP)
                cfg.MailTo = ConfigurationManager.AppSettings[typeName + "MailTo"];
            //cfg.MailFrom = cfg.ServerUsername;

            if (IsSecurityCfg())
            {
                WcfMail.EncryptionUtil enc = new WcfMail.EncryptionUtil();
                enc.key = enc.GetDefaultKey();
                cfg.ServerPassword = enc.DecryptData(enc.key, cfg.ServerPassword);
            }
            return cfg;
        }
    }
}
